package com.xiaoyu.lanling.feature.guard.controller

import `in`.srain.cube.views.list.CubeRecyclerViewAdapter
import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.view.list.BaseListViewController
import com.xiaoyu.lanling.event.guard.GiveUpGuardEvent
import com.xiaoyu.lanling.event.guard.GuardListEvent
import com.xiaoyu.lanling.feature.guard.data.GuardListData
import com.xiaoyu.lanling.feature.guard.datamodel.BaseGuardItem
import com.xiaoyu.lanling.feature.guard.viewholder.GuardViewHolderManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class GuardListController constructor(context: Context, listData: GuardListData, adapter: CubeRecyclerViewAdapter<BaseGuardItem>, swipeRefreshLayout: SwipeRefreshLayout?, recyclerView: RecyclerView) : BaseListViewController<BaseGuardItem, Any>(context, listData, adapter, swipeRefreshLayout, recyclerView) {

    companion object {
        fun create(context: Context, listData: GuardListData, swipeRefreshLayout: SwipeRefreshLayout?, recyclerView: RecyclerView): GuardListController {

            val adapter = CubeRecyclerViewSimpleAdapter<BaseGuardItem>()
            GuardViewHolderManager.bindViewHolder(adapter)

            val controller = GuardListController(context, listData, adapter, swipeRefreshLayout, recyclerView)

            AppEventBus.bindContainerAndHandler(context, object : SimpleEventHandler() {
                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onDataLoad(event: GuardListEvent) {
                    controller.onListEvent(event)
                }

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onEvent(event: GiveUpGuardEvent) {
                    if (!listData.isMyGuard) {
                        return
                    }
                    for ((index, guardItem) in listData.listPageInfo.dataList.withIndex()) {
                        if (guardItem.user == event.user) {
                            listData.listPageInfo.dataList.removeAt(index)
                            adapter.notifyItemRemoved(index)
                            return
                        }
                    }
                }
            })
            return controller
        }
    }
}